package com.yj.event_listener.contentObserver;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.Telephony;

import androidx.annotation.Nullable;

import com.yj.event_listener.interfaces.NotificationCallback;
import com.yj.event_listener.util.LogUtil;
import com.yj.event_listener.util.RemarkUtil;
import com.yj.event_listener.util.SmsUtil;

public class SmsContentObserver extends ContentObserver {

    private final Context context;
    private final NotificationCallback notificationCallback;

    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public SmsContentObserver(Handler handler, Context context, NotificationCallback callback) {
        super(handler);
        this.context = context;
        this.notificationCallback = callback;
    }


    @Override
    public void onChange(boolean selfChange) {
        LogUtil.d("onChange");
        onChange(selfChange, null);
    }

    @Override
    public void onChange(boolean selfChange, @Nullable Uri uri) {
        LogUtil.d("onChange "+uri);
//        super.onChange(selfChange, uri);
        Cursor cursor = SmsUtil.getFirstSMSMessage(context);
        // Process the cursor to get the first SMS message
        if (cursor != null && cursor.moveToFirst()) {
            // Retrieve message details
            long messageId = cursor.getLong(cursor.getColumnIndex(Telephony.Sms.THREAD_ID));
            String address = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String body = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            long date = cursor.getLong(cursor.getColumnIndex(Telephony.Sms.DATE));
            String title = cursor.getString(cursor.getColumnIndex(Telephony.Sms.CREATOR));

            String titleName = RemarkUtil.getSenderTitle(context, address);

            // Log the first SMS message details
            LogUtil.d("First SMS Message ID: " + messageId);
            LogUtil.d("Title: " + title);
            LogUtil.d("TitleName: "+ titleName);
            LogUtil.d("Address: " + address);
            LogUtil.d("Body: " + body);
            LogUtil.d("Date: " + date);

            if(notificationCallback != null){
                notificationCallback.onSms(titleName == null || titleName.isEmpty() ? address : titleName, body);
            }

            // Close the cursor
            cursor.close();
        }
    }
}
